# -*- coding: utf-8 -*-
# !/usr/bin/env python3

"""
@Author   : Leonis.Li
@Email    : leonis.li.ext@zeiss.com
@Cellphone:
@Version  : 1.0
@License  : Apache Licence
@Script   : ocr_service.py
@CreateAt : 2023/10/11 21:35
@UpdateAt : 2023/10/11 21:35
"""

import datetime
import time

from flask import Blueprint, current_app, jsonify, request

from .utils import ImagesUtils, PdfUtils, FILE_CACHE_PATH


# Create blueprint
ocr_v2_bp = Blueprint("ocr_api_v2", __name__, url_prefix='/api/v2')


@ocr_v2_bp.route("/", methods=["GET"])
def index():

    data = {
        "status": 200,
        "message": "OCR API(V2.0) text recognition service is running ...",
    }

    return jsonify(data)


@ocr_v2_bp.route("/image/analysis", methods=["POST"])
def ocr_rec_images():
    """ Recognize images with OCR & PPStructure
    """

    # Get data from form-data, Todo: picture type limits, like support ("*.jpeg", "*.png")
    image = request.files.get("image")
    # Language, default use chinese - model
    lang = request.form.get("language", "ch")
    # Extract target text from source, Optional source type in ("All", "Text", "Table", "Image")
    doc_object = request.form.get("doc_object", "ALL")

    # Log record
    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    current_app.logger.info(f"Stage-OcrRecTaskBaseInfo: upload image(filename: {image.filename}), "
                            f"choose language: {lang}, "
                            f"target doc_object: {doc_object.upper()}, "
                            f"time: {start_time}")

    # Cache image to FILE_CACHE_PATH
    ImagesUtils.cache_upload_image(filename=image.filename,
                                   cache_data=image.stream.read(),
                                   cache_path=FILE_CACHE_PATH
                                   )
    # Timer: upload image
    upload_end_at = time.time()

    # Model recognize: dict
    image_rec_text_data = ImagesUtils.get_recognize_text(language=lang,
                                                         rec_doc_object=doc_object,
                                                         image_cache_path=FILE_CACHE_PATH)

    # Log: model recognize time
    rec_model_end_at = time.time()
    current_app.logger.info("Stage-OcrRecTaskSummary: recognize text result from upload image, total cost: %.3f s " %
                            (rec_model_end_at - upload_end_at))

    # Parse result and return
    data = {
        "code": 200,
        "message": "Success",
        "data": {
            "filename": image.filename,
            "result": image_rec_text_data
            }
    }

    if not image_rec_text_data:
        # Recognize failed
        data["message"] = f"Recognize image file - {image.filename} failed"
        data["code"] = "1001"

    return jsonify(data)


@ocr_v2_bp.route("/pdf/analysis", methods=["POST"])
def ocr_rec_pdf():
    """ Recognize PDF with OCR & PPStructure """

    # Get data from form-data
    pdf = request.files.get("pdf")
    lang = request.form.get("language", "ch")
    doc_object = request.form.get("doc_object", "ALL")

    # Log record
    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    current_app.logger.info(f"Stage-OcrRecTaskBaseInfo: upload pdf (Filename: {pdf.filename}), "
                            f"choose language: {lang}, "
                            f"target doc_object: {doc_object.upper()}, "
                            f"time: {start_time}")

    # Timer
    start_at = time.time()

    # Convert to images, then cache images(Dont cache PDF file)
    PdfUtils.convert_pdf_to_images(pdf_stream=pdf.stream.read(), image_cache_path=FILE_CACHE_PATH)

    # Log record
    upload_end_at = time.time()
    current_app.logger.info("Stage-ConvertPdfTask: convert pdf to images, cost: %.3f s" % (upload_end_at - start_at))

    # Model recognize: dict
    pdf_rec_text_result = PdfUtils.get_recognize_text(language=lang,
                                                      rec_doc_object=doc_object,
                                                      image_cache_path=FILE_CACHE_PATH)
    # Log: model recognize time
    rec_model_end_at = time.time()
    current_app.logger.info("Stage-OcrRecTaskSummary: recognize text result from cache converted images, total cost: "
                            "%.3f s " % (rec_model_end_at - upload_end_at))

    # Parse result and return
    data = {
        "code": 200,
        "message": "Success",
        "data": {
            "filename": pdf.filename,
            "result": pdf_rec_text_result
            }
    }

    if not pdf_rec_text_result:
        # Recognize failed
        data["message"] = f"Recognize pdf file - {pdf.filename} failed."
        data["code"] = "1001"

    return jsonify(data)